﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using COFE.Core.Utils;
using System.ServiceModel;

namespace COFE.Web
{
    public static class WSFilterUtils
    {
        /// <summary>
        /// Get incoming uri's query part without the ? in front.
        /// </summary>
        /// <returns></returns>
        public static string GetQueryAsFilter(params string[] skippedParameters)
        {
            if (OperationContext.Current == null)
                return "";
            string query =
                Uri.UnescapeDataString(
                OperationContext.Current.IncomingMessageHeaders.To.Query
                .TrimStart('?'));
            ParamStringSerializer pss = new ParamStringSerializer(false);
            FilterStringSerializer fss = new FilterStringSerializer();
            return fss.PropertyToString(pss.StringToProperty(query)
                .Where(p => !skippedParameters.Contains(
                    p.Item1, StringComparer.OrdinalIgnoreCase)));
        }

        /// <summary>
        /// Create uri query part of string, 
        /// for used in /search?{output_of_this_command}
        /// </summary>
        /// <param name="skippedParameters"></param>
        /// <returns></returns>
        public static string GetFilterAsQuery(string filter, params string[] skippedParameters)
        {
            if (filter == null)
                throw new ArgumentException();
            if (OperationContext.Current == null)
                return "";
            ParamStringSerializer pss = new ParamStringSerializer(false);
            FilterStringSerializer fss = new FilterStringSerializer();
            string output = pss.PropertyToString(fss.StringToProperty(filter)
                .Where(p => !skippedParameters.Contains(
                    p.Item1, StringComparer.OrdinalIgnoreCase)));
            return output;
            //return Uri.EscapeDataString(output);
        }
    }
}
